import 'dart:async';
import 'dart:convert';
import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_is_know_dialog.dart';
import 'package:e_reception_flutter/constants/call_back.dart';
import 'package:e_reception_flutter/media_library/media_library_index/bean/js_response_bean.dart';
import 'package:e_reception_flutter/media_library/media_library_index/bean/poster_diy_info_bean.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/terminal_num_update_event.dart';
import 'package:e_reception_flutter/media_library/media_library_index/media_library_index_view_model.dart';
import 'package:e_reception_flutter/media_library/media_library_index/widgets/edit_poster_add_object_dialog.dart';
import 'package:e_reception_flutter/media_library/media_library_index/widgets/set_poster_content_dialog.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/ai_poster/ai_poster_index_view_model.dart';
import 'package:e_reception_flutter/ui/ai_poster/ai_poster_psd_list_bean.dart';
import 'package:e_reception_flutter/ui/ai_poster/change_to_diy_page_event.dart';
import 'package:e_reception_flutter/ui/ai_poster/poster_push_settings_page.dart';
import 'package:e_reception_flutter/ui/index/bean/index_bind_termainal_info.dart';
import 'package:e_reception_flutter/utils/file_utils.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_matisse_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_menu_widget/click_back_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:matisse_android_plugin/export_matisse.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_permission_lib.dart';
import 'package:vg_base/vg_save_util_lib.dart';
import 'package:vg_base/vg_screen_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'temp_empty_page.dart';
import 'ai_poster_index_response_bean.dart';

class EditAiPosterDetailPage extends StatefulWidget {
  static const ROUTER = "EditAiPosterDetailPage";

  final String url;
  final String hsn;
  //intoflg 01播放列表 02资源库 03海报模板库
  final String intoflg;
  final String psdJs;
  final String firstflg;//01第一次 02非一次性
  final String id;
  final Function(String diyPsd) callback;

  final AiPosterIndexListItemBean itemBean;

  final String name;
  final String address;
  final String logo;

  const EditAiPosterDetailPage(
      {Key key,
        @required this.url,
        this.itemBean,
        this.hsn,
        this.intoflg,
        this.psdJs,
        this.firstflg,
        this.id,
        this.callback,
        this.name,
        this.address,
        this.logo,
      })
      : assert(url != null, "currentItem must be not null");

  @override
  State<StatefulWidget> createState() => _EditAiPosterDetailPageState();

  static Future<String> navigatorPush(
      BuildContext context,
      String url,
      AiPosterIndexListItemBean itemBean,
      String hsn,
      String intoflg,
      String psdJs,
      String firstflg,
      {String id, Function(String diyPsd) callback, String name, String address, String logo}) {
    return RouterUtils.routeForFutureResult(
        context,
        EditAiPosterDetailPage(
          url: url,
          itemBean:itemBean,
          hsn: hsn,
          intoflg: intoflg,
          psdJs: psdJs,
          firstflg: firstflg,
          id: id,
          callback: callback,
          name: name,
          address: address,
          logo: logo,
        ),
        routeName: EditAiPosterDetailPage.ROUTER
    );
  }
}

class _EditAiPosterDetailPageState extends BaseState<EditAiPosterDetailPage> {
  MediaLibraryIndexViewModel _viewModel;
  AiPosterIndexViewModel _aiPosterViewModel;
  WebViewController _webViewController;
  //webview加载成功
  bool isUrlLoadComplete = false;
  JsResponseBean _imageJsResponseBean;
  JsResponseBean _contentJsResponseBean;
  //底部弹出布局
  bool showBottomSheet = false;
  bool showEditImageSheet = false;
  bool showChangeColorSheet = false;
  String _content;
  ///这俩都完成才能走保存接口
  //图片数据是否回调完成
  bool _saveImageData = false;
  //diy数据是否回调完成
  bool _saveEditData = false;
  String _psd;
  //原始psd
  String _originPsd;
  //变化的psd
  String _changePsd;
  String _imagePath;
  String _firsrflg;
  List<String> _diyCancelDataList = new List();
  List<String> _diyRecoverDataList = new List();
  // //操作处于第几步，用户记录撤销相关
  // int _cancelOperationIndex = 0;
  // //操作处于第几步，用户记录恢复相关
  // int _recoverOperationIndex = 0;
  AiPosterIndexListItemBean _itemBean;
  List<AiPosterPsdListBean> _multiColorList;
  ScrollController _horizontalController;
  int _selectIndex = 0;
  int _tempSelectIndex = 0;
  ValueNotifier<int> _initPageNotifier;
  int _allTerminalSize = 0;
  StreamSubscription _terminalNumRefreshSubscription;
  @override
  void initState() {
    super.initState();
    _psd = widget?.psdJs;
    _originPsd = widget?.psdJs;
    _changePsd = widget?.psdJs;
    _itemBean = widget?.itemBean;
    if(StringUtils.isNotEmpty(_psd)){
      _diyCancelDataList.add(_psd);
      _diyRecoverDataList.add(_psd);
    }
    if(StringUtils.isNotEmpty(_itemBean?.psdurl)) {
      List response = json.decode(_itemBean?.psdurl);
      _multiColorList = List()
        ..addAll(
            response.map((o) => AiPosterPsdListBean.fromMap(o))
        );
      if (_multiColorList != null && _multiColorList.length > 0) {
        // String psdJson = json.encode(_multiColorList[0].data);
        for (int i = 0; i < _multiColorList.length; i++) {
          List<PsdDateBean> data = _multiColorList[i].data;
          for (int j = 0; j < data.length; j++) {
            PsdDateBean psdData = data[j];
            if (psdData?.name?.contains("地址-") &&
                StringUtils.isNotEmpty(widget?.address)) {
              psdData?.content = widget?.address;
            }
            if (psdData?.name?.contains("名称-") &&
                StringUtils.isNotEmpty(widget?.name)) {
              psdData?.content = widget?.name;
            }
            if (psdData?.name?.contains("logo-") &&
                StringUtils.isNotEmpty(widget?.logo)) {
              psdData?.content = widget?.logo;
            }
            data[j] = psdData;
          }
          _multiColorList[i].data = data;
          _multiColorList[i].dataJson = json.encode(data);
        }
      }
    }
    _horizontalController= ScrollController();
    _firsrflg = widget?.firstflg;
    MediaLibraryIndexViewModel.EMPTY_FLAG = false;
    _viewModel = MediaLibraryIndexViewModel(this);
    _aiPosterViewModel = AiPosterIndexViewModel(this);
    _viewModel.getPosterDiyInfo(context, _itemBean?.getPicId(), widget?.intoflg);
    String cacheKey = UserRepository.getInstance().getHomePunchAndTerminalInfoCacheKey();
    ///获取缓存数据
    Future<String> future = SharePreferenceUtil.getString(cacheKey);
    future.then((jsonStr){
      if(!StringUtils.isEmpty(jsonStr)){
        setState(() {
          Map map = json.decode(jsonStr);
          IndexBindTermainalInfo bean = IndexBindTermainalInfo.fromMap(map);
          if(bean != null){
            if(bean.data != null
                && bean.data.bindTerminalList != null){
              _allTerminalSize = bean.data.bindTerminalList.length;
            }
          }
        });
      }
    });
    _terminalNumRefreshSubscription = VgEventBus.global.streamController.stream.listen((event) {
      if(event is TerminalNumRefreshEvent){
        _allTerminalSize = event?.num??0;
      }
    });
    _initPageNotifier = new ValueNotifier(_tempSelectIndex);
    _viewModel.posterLook(_itemBean?.picid, "03");
  }

  @override
  void dispose() {
    _initPageNotifier?.dispose();
    _terminalNumRefreshSubscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return CustomAnnotatedRegion(
      WillPopScope(
        onWillPop: _withdrawFront,
        child: Scaffold(
          backgroundColor: Colors.black,
          resizeToAvoidBottomPadding: false,
          resizeToAvoidBottomInset: false,
          body: Column(
              mainAxisSize: MainAxisSize.min,
              children:[
                _toTopBarWidget(),
                SizedBox(height: 10,),
                Expanded(
                  child: GestureDetector(
                      onTap: (){
                        setState(() {
                          showBottomSheet = false;
                          showEditImageSheet = false;
                        });
                      },
                      child: _toPlaceHolderWidget()
                  ),
                ),
                SizedBox(height: ScreenUtils.getBottomBarH(context),)
              ]),
        ),
      ),
      navigationBarColor: Color(0xFFF6f7F9),
      navigationBarIconBrightness: Brightness.dark,
    );
  }

  Future<bool> _withdrawFront() async {
    if((_originPsd??"") == (_changePsd??"")){
      //直接返回
      return true;
    }
    bool result =
    await CommonConfirmCancelDialog.navigatorPushDialog(context,
        title: "提示",
        content: "确认放弃此次编辑吗？",
        cancelText: "取消",
        confirmText: "确定",
        confirmBgColor: ThemeRepository.getInstance()
            .getPrimaryColor_1890FF());
    //去裁剪
    if(result??false){
      return true;
    }
    return false;
  }

  void onBackPressed()async{
    if((_originPsd??"") == (_changePsd??"")){
      //直接返回
      RouterUtils.pop(context);
      return;
    }
    bool result =
        await CommonConfirmCancelDialog.navigatorPushDialog(context,
        title: "提示",
        content: "确认放弃此次编辑吗？",
        cancelText: "取消",
        confirmText: "确定",
        confirmBgColor: ThemeRepository.getInstance()
            .getPrimaryColor_1890FF());
    //去裁剪
    if(result??false){
      RouterUtils.pop(context);
    }

  }



  Widget _toTopBarWidget() {
    return Container(
      color: Colors.transparent,
      padding: EdgeInsets.only(top: ScreenUtils.getStatusBarH(context)),
      child: Container(
        height: 44,
        child: Row(
          children: [
            ClickAnimateWidget(
              child: Container(
                width: 40,
                height: 44,
                alignment: Alignment.centerLeft,
                padding: const EdgeInsets.only(left: 15.6),
                child: Image.asset(
                  "images/top_bar_back_ico.png",
                  width: 9,
                  color: Color(0xFF5E687C),
                ),
              ),
              scale: 1.4,
              onClick: () {
                if(showChangeColorSheet){
                  return;
                }
                onBackPressed();
              },
            ),
            Text(
              "编辑",
              style: TextStyle(
                  fontSize: 17,
                  color: ThemeRepository.getInstance().getTextColor_D0E0F7()
              ),
            ),
            Spacer(),
            ClickAnimateWidget(
              child: Container(
                width: 40,
                height: 44,
                alignment: Alignment.centerLeft,
                padding: const EdgeInsets.only(left: 10.5, right: 10.5),
                child: Image.asset(
                  "images/icon_cancel_edit.png",
                  width: 19,
                  color: (_diyCancelDataList?.length == 1)?Color(0xFF5E687C):Colors.white,
                ),
              ),
              scale: 1.4,
              onClick: () {
                if(showChangeColorSheet){
                  return;
                }
                if(_diyCancelDataList?.length == 1){
                  return;
                }
                //获取最后一个可撤销的
                String recoverOperationJs = _diyCancelDataList?.last;
                //移除他
                _diyCancelDataList.removeLast();
                String operationJs = _diyCancelDataList?.last;
                //把他加到可恢复的列表
                _diyRecoverDataList.add(recoverOperationJs);
                //执行js
                _setPsd(operationJs);
                setState(() { });
              },
            ),
            ClickAnimateWidget(
              child: Container(
                width: 40,
                height: 44,
                alignment: Alignment.centerLeft,
                padding: const EdgeInsets.only(left: 10.5, right: 10.5),
                child: Image.asset(
                  "images/icon_recover_edit.png",
                  width: 19,
                  color: (_diyRecoverDataList?.length == 1)?Color(0xFF5E687C):Colors.white,
                ),
              ),
              scale: 1.4,
              onClick: () {
                if(showChangeColorSheet){
                  return;
                }
                if(_diyRecoverDataList?.length == 1){
                  return;
                }

                String operationJs = _diyRecoverDataList.removeLast();
                _diyCancelDataList.add(operationJs);
                _setPsd(operationJs);
                setState(() { });
              },
            ),
            SizedBox(width: 10,),
            _toSaveButtonWidget(),
            SizedBox(width: 15,),
          ],
        ),
      ),
    );
  }

  Widget _toSaveButtonWidget() {
    return CommonFixedHeightConfirmButtonWidget(
      isAlive: true,
      width: 48,
      height: 24,
      unSelectBgColor:
      ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
      selectedBgColor:
      ThemeRepository.getInstance().getPrimaryColor_1890FF(),
      unSelectTextStyle: TextStyle(
          color: VgColors.INPUT_BG_COLOR,
          fontSize: 12,
          fontWeight: FontWeight.w600),
      selectedTextStyle: TextStyle(
          color: Colors.white, fontSize: 12, fontWeight: FontWeight.w600),
      text: "保存",
      onTap: (){
        if(showChangeColorSheet){
          return;
        }
        _save();
        // print("点击");
        // String msg = uploadBean?.checkVerify();
        // if(StringUtils.isEmpty(msg)){
        //   _viewModel.setBasicInfo(context, _uploadValueNotifier.value);
        //   return;
        // }
        // VgToastUtils.toast(context, msg);
      },
    );
  }



  ///加载中
  Widget _toPlaceHolderWidget() {
    double paddingBottom = 0;
    if("01" != _itemBean?.colorflg || _multiColorList == null || _multiColorList.length == 0){
      paddingBottom = 50 + ScreenUtils.getBottomBarH(context) + 15;
    }else{
      paddingBottom = 50 + 50 + ScreenUtils.getBottomBarH(context) + 15;
    }
    return ValueListenableBuilder(
      valueListenable: _viewModel?.statusTypeValueNotifier,
      builder:
          (BuildContext context, PlaceHolderStatusType value, Widget child) {
        return VgPlaceHolderStatusWidget(
          loadingStatus: value == PlaceHolderStatusType.loading,
          loadingCustomWidget: Container(
            padding: EdgeInsets.only(
                bottom: paddingBottom),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                CircularProgressIndicator(
                  strokeWidth: 2,
                ),
                SizedBox(
                  height: 10,
                ),
                Text(
                  "正在加载",
                  style: TextStyle(
                      color: ThemeRepository.getInstance()
                          .getTextBFC2CC_BFC2CC(),
                      fontSize: 10),
                )
              ],
            ),
          ),
          errorStatus: value == PlaceHolderStatusType.error,
          errorOnClick: () => _viewModel.getPosterDiyInfo(context, _itemBean?.getPicId(), widget?.intoflg),
          loadingOnClick: () => _viewModel.getPosterDiyInfo(context, _itemBean?.getPicId(), widget?.intoflg),
          child: child,
        );
      },
      child: Stack(
        children: [
          Align(
              alignment: Alignment.topCenter,
              child: _toInfoWidget()
          ),
          Visibility(
            visible: !isUrlLoadComplete,
            child: Center(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  CircularProgressIndicator(
                    strokeWidth: 2,
                    // valueColor:ColorTween(begin: Colors.white, end: Colors.red[900]).animate(null),
                    // backgroundColor:(topInfo?.PVCnt?.punchcnt ?? 0)==0? Colors.transparent: Colors.white,
                    // value: _value/190,
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  Text(
                    "正在加载",
                    style: TextStyle(
                        color: ThemeRepository.getInstance()
                            .getTextBFC2CC_BFC2CC(),
                        fontSize: 10),
                  )
                ],
              ),
            ),
          ),
          _showNewAddObject(),
          _showBottomSheet(),
          _showEditImageSheet(),
          _showChangeColorSheet(),
        ],
      ),
    );
  }

  Widget _toInfoWidget(){
    return ValueListenableBuilder(
        valueListenable: _viewModel?.diyInfoNotifier,
        builder: (BuildContext context,
            ComPicDiyBean picDiyBean, Widget child) {
          // return _toWebViewWidget(picDiyBean);
          if("01" != _itemBean?.colorflg || _multiColorList == null || _multiColorList.length == 0){
            return _toWebViewWidget(picDiyBean);
          }else{
            return Column(
              children: [
                _toWebViewWidget(picDiyBean, colorHeight: 126),
                _toChangeColorWidget(_multiColorList?.elementAt(_selectIndex)),
              ],
            );
          }
        });
  }

  Widget _toWebViewWidget(ComPicDiyBean picDiyBean, {double colorHeight}) {
    double maxHeight = ScreenUtils.screenH(context) -
        ScreenUtils.getStatusBarH(context) -
        ScreenUtils.getBottomBarH(context) - 44 - (colorHeight??0);
    double screenWidth = ScreenUtils.screenW(context) - 30;
    double width;
    double height;
    if (maxHeight / screenWidth <= 16 / 9) {
      width = maxHeight / (16 / 9);
      height = maxHeight;
    } else {
      width = screenWidth;
      height = screenWidth * (16 / 9);
    }
    print("屏幕宽： ${screenWidth}");
    print("屏幕高： ${maxHeight}");
    print("真实宽： ${width}");
    print("真实高： ${height}");
    String url = widget?.url??"";
    // String url = "http://etpic.we17.com/test/20210728165000_7761.html?downloadflg=01&name=%E8%94%9A%E6%9D%A5%E6%97%A0%E9%99%90%E5%9F%B9%E8%AE%AD%E5%93%A6&address=%E4%B8%B0%E5%8F%B0%E5%8C%BA%E6%90%9C%E5%AE%9D%E5%95%86%E5%8A%A1%E4%B8%AD%E5%BF%83%E5%B2%81&logo=http%3A%2F%2Fetpic.we17.com%2Ftest%2F20210520180047_2080.jpg&is_edit=01";
    if(picDiyBean != null && StringUtils.isNotEmpty(picDiyBean.diytext)){
      url = url + "&diyjson=${Uri.encodeComponent(picDiyBean.diytext)}";
    }
    print("url:$url");

    return Container(
      width: width,
      height: height,
      alignment: Alignment.center,
      child: ClipRRect(
        borderRadius: BorderRadius.all(Radius.circular(4)),
        child: Opacity(
          opacity: isUrlLoadComplete ? 1 : 0,
          child: WebView(
            initialUrl: url,
            javascriptMode: JavascriptMode.unrestricted,
            javascriptChannels: <JavascriptChannel>[
              _clickTextChannel(context),
              _clickImageChannel(context),
              _closeBottomMenuChannel(context),
              _getSaveContent(context),
              _getSaveEditData(context),
              _getDiyDataList(context),
              _doubleClickText(context),
            ].toSet(),
            onPageFinished: (String url) {
              print("加载完成\n" + url);
              _setPsd(_psd);
              setState(() {
                isUrlLoadComplete = true;
              });
              // setState(() {
              //   _isLoading = false;
              //   setState(() {
              //
              //   });
              // });
            },
            onWebViewCreated: (controller) {
              _webViewController = controller;
            },
            // gestureRecognizers: Set()
            //   ..add(
            //     Factory<TapGestureRecognizer>(
            //           () => tapGestureRecognizer,
            //     ),
            //   ),
          ),
        ),
      ),
    );
  }



  Widget _toChangeColorWidget(AiPosterPsdListBean itemBean){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        setState(() {
          showChangeColorSheet = !showChangeColorSheet;
        });
      },
      child: Container(
        height: 50,
        margin: EdgeInsets.only(right: 20),
        alignment: Alignment.centerRight,
        color: Colors.transparent,
        child: ClipRRect(
          borderRadius: BorderRadius.circular(2),
          child: Container(
            height: 36,
            width: 50,
            decoration: BoxDecoration(color: Color(0x33F5F6F9)),
            child: Row(
              children: [
                VgCacheNetWorkImage(
                  itemBean?.cover ?? "",
                  height: 36,
                  width: 36,
                  fit: BoxFit.cover,
                  imageQualityType: ImageQualityType.middleDown,
                ),
                Container(
                  height: 36,
                  width: 14,
                  alignment: Alignment.center,
                  child: Image.asset("images/icon_change_color.png", width: 8,),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }


  Widget _toGridItemWidget(
      BuildContext context, AiPosterPsdListBean itemBean, int index) {
    return ClickBackgroundWidget(
      backgroundColor: Colors.transparent,
      selectColor: Colors.transparent,
      behavior: HitTestBehavior.translucent,
      onTap: () {
        // if(_selectIndex != index){
        _tempSelectIndex = index;
        _initPageNotifier.value = _tempSelectIndex;
        String psdJson = _multiColorList[index].dataJson;
        String js = "get_data('${psdJson}')";
        _setPsd(js);
        // }
      },
      child:ValueListenableBuilder(
        valueListenable: _initPageNotifier,
        builder: (BuildContext context, int changedIndex, Widget child){
          return Column(
            children: [
              Visibility(
                visible: index == changedIndex,
                child: Image(
                  image: AssetImage("images/icon_poster_selected.png"),
                  width: 14,
                  height: 7,
                  color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                ),
              ),
              (index == changedIndex)?SizedBox(height: 4,):SizedBox(height: 11,),
              Container(
                decoration: BoxDecoration(
                    border: Border.all(
                        color: (index == changedIndex)?Color(0XFFFFFFFF):Color(0xFFF6F7F9),
                        width: (index == changedIndex)? 2:2),
                    borderRadius: BorderRadius.circular(4),
                    boxShadow: (index == changedIndex)?[
                      BoxShadow(
                          color: Color(0x1AFFFFFF),
                          offset: Offset(0, -1),
                          blurRadius: 1),
                      BoxShadow(
                          color: Color(0x1AFFFFFF),
                          offset: Offset(-1, 0),
                          blurRadius: 1),
                    ]:null
                ),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(4),
                  child: Container(
                    height: (((ScreenUtils.screenW(context) - 15 - 16) / 5.5) * 103 / 60) -3,
                    color: Colors.transparent,
                    child: VgCacheNetWorkImage(
                      itemBean?.cover ?? "",
                      fit: BoxFit.contain,
                      imageQualityType: ImageQualityType.middleDown,
                    ),
                  ),
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  _setPsd(String psdJson){
    print("js:" + psdJson);
    psdJson = psdJson.replaceAll("\\n", "<br/>");
    psdJson = psdJson.replaceAll("\\r", "<br/>");
    _changePsd = psdJson;
    _webViewController?.evaluateJavascript(psdJson);
  }

  //改变文字
  _editText(String content, int index) {
    String js = ("get_text('${content}'"+",'${index}')").replaceAll("\n", "<br/>");
    print("_editText:" + js);
    _webViewController?.evaluateJavascript(js);
  }

  //改变图片
  _editImage(String picurl, int index) {
    String js = ("get_image('${picurl}'"+",'${index}')").replaceAll("\n", "<br/>");
    print("_editImage:" + js);
    _webViewController?.evaluateJavascript(js);
  }


  //保存
  _save(){
    _saveImageData = false;
    _saveEditData = false;
    loading(true, msg: "保存中");
    _webViewController?.evaluateJavascript('save_diy()');
    _webViewController?.evaluateJavascript('save_edit_data()');
  }

  ///复制
  _copyObject(){
    _webViewController?.evaluateJavascript('copy_obj()');
  }

  ///复制
  _deleteObject(){
    _webViewController?.evaluateJavascript('delete_obj()');
  }


  //编辑文字
  JavascriptChannel _clickTextChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'editText',
        onMessageReceived: (JavascriptMessage message) {
          print("收到了点击文字的js回调");
          print(message.message);
          Map map = json.decode(message.message);
          JsResponseBean jsResponseBean = JsResponseBean.fromMap(map);
          if(jsResponseBean != null && StringUtils.isNotEmpty(jsResponseBean.content)){
            //点击图片
            //点击文字
            _contentJsResponseBean = jsResponseBean;
            String tempContent = _contentJsResponseBean?.content??"";
            if(tempContent.contains("<br/>")){
              tempContent = tempContent.replaceAll("<br/>", "\n");
            }
            if(tempContent.contains("<br>")){
              tempContent = tempContent.replaceAll("<br>", "\n");
            }
            if(tempContent.contains("</div>")){
              tempContent = tempContent.replaceAll("</div>", "");
            }
            _content = tempContent;
            if(showBottomSheet != true){
              showBottomSheet = true;
            }
            setState(() {});
            // EditPosterTextFunctionDialog.navigatorPushDialog(
            //   context,
            //   tempContent,
            //   changeText: (content){
            //     _changeText(content);
            //   },
            //   showStyle: (){
            //     _changeStyle();
            //   },
            //   align: (){
            //
            //   },
            //   copy: (){
            //
            //   },
            //   delete: (){
            //
            //   }
            // );
            return;
          }
        });
  }


  //编辑图片
  JavascriptChannel _clickImageChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'editImage',
        onMessageReceived: (JavascriptMessage message) {
          print("收到了点击图片的js回调");
          print(message.message);
          Map map = json.decode(message.message);
          JsResponseBean jsResponseBean = JsResponseBean.fromMap(map);
          if(jsResponseBean != null){
            _imageJsResponseBean = JsResponseBean();
            _imageJsResponseBean.index = jsResponseBean.index;
            _imageJsResponseBean.proportion = jsResponseBean.proportion;
          }
          if(_imageJsResponseBean != null){
            if(showEditImageSheet != true){
              showEditImageSheet = true;
            }
            setState(() {});
            // EditPosterImageFunctionDialog.navigatorPushDialog(
            //     context,
            //     changeImage: (picurl){
            //       _changeImage(picurl);
            //     },
            //     showStyle: (){
            //       _changeStyle();
            //     },
            //     copy: (){
            //
            //     },
            //     delete: (){
            //
            //     }
            // );
          }
        });
  }

  JavascriptChannel _closeBottomMenuChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'closeBottomMenu',
        onMessageReceived: (JavascriptMessage message) {
          print("收到了隐藏菜单的js回调");
          print(message.message);
          setState(() {
            showBottomSheet = false;
            showEditImageSheet = false;
          });
        });
  }

  //获取要上传的信息
  JavascriptChannel _getSaveContent(BuildContext context) {
    return JavascriptChannel(
        name: 'saveDiyData',
        onMessageReceived: (JavascriptMessage message) async{
          print("收到了diy图片完成的js回调" + message.message);
          if (message != null &&
              StringUtils.isNotEmpty(message.message) &&
              message.message.contains(",")) {
            String base64Str = message.message.split(",")[1];
            //下载
            SaveUtils.saveImage(base64Url: base64Str);
            String imagePath =
            await FileUtils.createFileFromString(base64Str);
            if (StringUtils.isNotEmpty(imagePath)) {
              _imagePath = imagePath;
              _saveImageData = true;
              String psdJson = _psd?.replaceAll("get_data('", "");
              psdJson = psdJson?.replaceAll("')", "");
              if(_saveEditData && _saveImageData){
                //01第一次 02非第一次
                if("02" == widget?.firstflg){
                  _aiPosterViewModel.updateUserDiyPic(context, widget?.id,
                      _imagePath, psdJson, (pic){
                        if(widget?.callback != null){
                          String js = "get_data('${_psd}')";
                          widget?.callback?.call(js);
                        }
                        RouterUtils.pop(context, result: pic);
                      });
                }else{
                  _aiPosterViewModel.saveUserDiyPic(context, _itemBean?.compicid,
                      _itemBean?.getPicId(), _imagePath, psdJson, _firsrflg, (pic, id){
                        //直接在当前页面弹
                        _showPushDialog(pic, id);
                        _firsrflg = "02";
                        setState(() {
                          _diyCancelDataList.clear();
                          _diyRecoverDataList.clear();
                          if(StringUtils.isNotEmpty(_psd)){
                            _diyCancelDataList.add(_psd);
                            _diyRecoverDataList.add(_psd);
                          }
                        });
                      });
                }
                //intoflg 01播放列表 02资源库 03海报模板库
                _viewModel.downloadSharePoster("", _itemBean?.getPicId(), "03", "01", "");
              }
            }

          } else {
            toast("下载失败，请重试");
            loading(false);
          }
        });
  }

  void _showPushDialog(String pic, String id)async{
    if("01" == _itemBean?.useflg){
      //如果有终端正在使用
      return;
    }
    CommonConfirmCancelDialog.navigatorPushDialog(context,
      title: "提示",
      content: "已保存至手机相册，你也可以立即投屏播放",
      cancelText: "暂不投屏",
      confirmText: "立即投屏",
      confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
      onPop: (){
        RouterUtils.pop(context);
        VgEventBus.global.send(new ChangeToDiyPageEvent());
        RouterUtils.pop(context);
      },
      onConfrim: (){
        RouterUtils.pop(context);
        if(_allTerminalSize >= 1){
          //一个是模板制作的，一个是从已制作的
          String tempId = id;
          if(StringUtils.isEmpty(tempId)){
            tempId = _itemBean?.id;
          }
          PosterPushSettingsPage.navigatorPush(context, _itemBean?.getPicId(), pic, tempId);
        }else{
          CommonISeeDialog.navigatorPushDialog(context, content: "暂无可投屏的显示屏");
        }
      },
    );
  }

  JavascriptChannel _getSaveEditData(BuildContext context) {
    return JavascriptChannel(
        name: 'saveEditData',
        onMessageReceived: (JavascriptMessage message) async{
          print("收到了编辑海报数据的回调" + message.message);
          if (message != null &&
              StringUtils.isNotEmpty(message.message)) {
            _psd = message.message;
            _saveEditData = true;
            String psdJson = _psd?.replaceAll("get_data('", "");
            psdJson = psdJson?.replaceAll("')", "");
            if(_saveEditData && _saveImageData){
              //01第一次 02非第一次
              if("02" == widget?.firstflg){
                _aiPosterViewModel.updateUserDiyPic(context, widget?.id,
                    _imagePath, psdJson, (pic){
                      if(widget?.callback != null){
                        String js = "get_data('${_psd}')";
                        widget?.callback?.call(js);
                      }
                      RouterUtils.pop(context, result: pic);
                    });
              }else{
                _aiPosterViewModel.saveUserDiyPic(context, _itemBean?.compicid,
                    _itemBean?.getPicId(), _imagePath, psdJson, _firsrflg, (pic, id){
                      //直接在当前页面弹
                      _showPushDialog(pic, id);
                      _firsrflg = "02";
                      setState(() {
                        _diyCancelDataList.clear();
                        _diyRecoverDataList.clear();
                        if(StringUtils.isNotEmpty(_psd)){
                          _diyCancelDataList.add(_psd);
                          _diyRecoverDataList.add(_psd);
                        }
                      });
                    });
              }

              //intoflg 01播放列表 02资源库 03海报模板库
              _viewModel.downloadSharePoster("", _itemBean?.getPicId(), "03", "01", "");
            }
          } else {
            toast("下载失败，请重试");
            loading(false);
          }
        });
  }

  JavascriptChannel _getDiyDataList(BuildContext context) {
    return JavascriptChannel(
        name: 'updateDiyDataList',
        onMessageReceived: (JavascriptMessage message) async{
          print("收到了编辑海报数据变化的回调" + message.message);
          if (message != null &&
              StringUtils.isNotEmpty(message.message)) {
            String js = "get_data('${message.message}')";
            _changePsd = js;
            // if(_diyDataList.contains(js)){
            //   print("重复数据，不记录");
            // }else{
            setState(() {
              _diyCancelDataList.add(js);
            });
            // }
          } else {
            toast("下载失败，请重试");
            loading(false);
          }
        });
  }

  ///双击文字
  JavascriptChannel _doubleClickText(BuildContext context) {
    return JavascriptChannel(
        name: 'doubleClickText',
        onMessageReceived: (JavascriptMessage message) async{
          print("收到双击文字的回调" + message.message);
          print(message.message);
          Map map = json.decode(message.message);
          JsResponseBean jsResponseBean = JsResponseBean.fromMap(map);
          if(jsResponseBean != null && StringUtils.isNotEmpty(jsResponseBean.content)){
            //点击图片
            //点击文字
            _contentJsResponseBean = jsResponseBean;
            String tempContent = _contentJsResponseBean?.content??"";
            if(tempContent.contains("<br/>")){
              tempContent = tempContent.replaceAll("<br/>", "\n");
            }
            if(tempContent.contains("<br>")){
              tempContent = tempContent.replaceAll("<br>", "\n");
            }
            if(tempContent.contains("</div>")){
              tempContent = tempContent.replaceAll("</div>", "");
            }
            _content = tempContent;
            if(showBottomSheet != true){
              showBottomSheet = true;
            }
            SetPosterContentDialog.navigatorPushDialog(context,
                content: _content,
                onConfirm: (content){
                  _changeText(content);
                });
            setState(() {});
            return;
          }
        });
  }


  //改字
  _changeText(content){
    _editText(content, _contentJsResponseBean?.index);
  }
  //样式
  _changeStyle(){

  }
  //对齐
  _changeAlign(){

  }


  //改图
  _changeImage(picurl){
    _editImage(picurl, _imageJsResponseBean.index);
  }


  ///新增项目相关
  _showNewAddObject(){
    return Align(
      alignment: Alignment.bottomCenter,
      child: Container(
        padding: MediaQuery.of(context).viewInsets, //边距（必要）
        decoration: BoxDecoration(
            color: Color(0xFF333333)
        ),
        child: _toCommonBaseWidget("添加元素", "icon_add_object", _addObject),

        // Column(
        //   mainAxisSize : MainAxisSize.min,
        //   children: [
        //     Container(
        //       child: Row(
        //         children: <Widget>[
        //           _toCommonBaseWidget("更换模板", "icon_change_module", _changeModule),
        //           Container(
        //             height: 24,
        //             width: 1,
        //             color: Color(0xFF505050),
        //           ),
        //           _toCommonBaseWidget("添加元素", "icon_add_object", _addObject),
        //         ],
        //       ),
        //     ),
        //   ],
        // ),
      ),
    );
  }

  Widget _toCommonBaseWidget(String name, String icon, VoidCallback callback){
    return Container(
      height: 50,
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          callback.call();
        },
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(
              "images/${icon}.png",
              height: 22,
              width: 22,
            ),
            SizedBox(
              width: 6,
            ),
            Text(
                name,
                style: TextStyle(
                  fontSize: 13,
                  color: Colors.white,
                )
            ),
          ],
        ),
      ),
    );
  }


  ///更换模板
  _changeModule() {
    TempEmptyPage.navigatorPush(context);
    // VgToastUtils.toast(context, "敬请期待");
  }

  ///添加元素
  _addObject() {
    EditPosterAddObjectDialog.navigatorPushDialog(context, _addText, _addImage);
  }

  ///新增文字元素
  _addText(String content){
    String js = "add_text('${content}')";
    print("js:" + js);
    _webViewController?.evaluateJavascript(js);
  }

  ///新增图片元素
  _addImage(String picurl){
    String js = "add_image('${picurl}')";
    _webViewController?.evaluateJavascript(js);
  }


  //弹起底部布局
  _showBottomSheet(){
    return Visibility(
      visible: showBottomSheet,
      child: Align(
        alignment: Alignment.bottomCenter,
        child: AnimatedPadding(
          padding: MediaQuery.of(context).viewInsets, //边距（必要）
          duration: const Duration(milliseconds: 100), //时常 （必要）
          child: Container(
            decoration: BoxDecoration(
                color: Color(0xFFF6f7F9)
            ),
            child: Column(
              mainAxisSize : MainAxisSize.min,
              children: [
                Container(
                  padding: EdgeInsets.only(top: 14, bottom: 14, left: 0, right: 0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      _toCommonFunctionWidget("icon_poster_change_text", "icon_poster_change_text_selected",  "改字",),
                      _toCommonFunctionWidget("icon_poster_change_style", "icon_poster_change_style_selected", "样式", ),
                      _toCommonFunctionWidget("icon_poster_change_align", "icon_poster_change_align_selected", "对齐", ),
                      _toCommonFunctionWidget("icon_poster_copy", "icon_poster_change_text_selected", "复制", ),
                      _toCommonFunctionWidget("icon_poster_delete", "icon_poster_change_text_selected", "删除", ),
                    ],
                  ),
                ),
                // _toSetTextWidget(),
                // _toChangeTextStyleWidget(),
                // __toChangeAlignWidget(),

              ],
            ),
          ),
        ),
      ),
    );
  }

  ///通用样式
  Widget _toCommonFunctionWidget(String asset, String selectAsset, String title){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        if("改字" == title){
          SetPosterContentDialog.navigatorPushDialog(context,
              content: _content,
              onConfirm: (content){
                _content = content;
                _changeText(content);
              });
          return;
        }
        if("复制" == title){
          _copyObject();
          return;
        }
        if("删除" == title){
          _deleteObject();
          return;
        }
        TempEmptyPage.navigatorPush(context);
        // VgToastUtils.toast(context, "敬请期待");

      },
      child: Container(
        width: (ScreenUtils.screenW(context) - 56)/5,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(
              "images/${asset}.png",
              width: 19,
            ),
            SizedBox(height: 5,),
            Text(
              title,
              style: TextStyle(
                color: ThemeRepository.getInstance().getLineColor_3A3F50(),
                fontSize: 10,
              ),
            ),
          ],
        ),
      ),
    );
  }


  //弹起改图布局
  _showEditImageSheet(){
    return Visibility(
      visible: showEditImageSheet,
      child: Align(
        alignment: Alignment.bottomCenter,
        child: AnimatedPadding(
          padding: MediaQuery.of(context).viewInsets, //边距（必要）
          duration: const Duration(milliseconds: 100),
          child: Container(
            padding: EdgeInsets.only(top: 14, bottom: 14, left: 40, right: 40),
            decoration: BoxDecoration(
                color: Color(0xFFF6f7F9)
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                _toImageFunctionWidget("icon_poster_change_image", "换图"),
                _toImageFunctionWidget("icon_poster_clip", "裁剪"),
                _toImageFunctionWidget("icon_poster_copy", "复制"),
                _toImageFunctionWidget("icon_poster_delete", "删除"),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _toImageFunctionWidget(String asset, String title){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        if("换图" == title){
          if(_imageJsResponseBean != null && StringUtils.isNotEmpty(_imageJsResponseBean.proportion)){
            //有比例裁剪
            int scalex = 9;
            int scaley = 16;
            List<String> scaleList = _imageJsResponseBean.proportion.split(":");
            if(scaleList != null && scaleList.isNotEmpty && scaleList.length == 2){
              scalex = int.parse(scaleList[0]);
              scaley = int.parse(scaleList[1]);
              _chooseSinglePicAndClip(scalex, scaley);
            }else{
              //直接上传
              _chooseSinglePic();
            }
          }else{
            //直接上传
            _chooseSinglePic();
          }
        }else{
          TempEmptyPage.navigatorPush(context);
          // VgToastUtils.toast(context, "敬请期待");
        }

      },
      child: Column(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(
            "images/${asset}.png",
            width: 19,
          ),
          SizedBox(height: 5,),
          Text(
            title,
            style: TextStyle(
              color: ThemeRepository.getInstance().getLineColor_3A3F50(),
              fontSize: 10,
            ),
          ),
        ],
      ),
    );
  }

  void _chooseSinglePic() async {
    String fileUrl;
    List<String> list = await MatisseUtil.selectPhoto(context: context,maxSize: 1,
        onRequestPermission: (msg)async{
          bool result =
          await CommonConfirmCancelDialog.navigatorPushDialog(context,
            title: "提示",
            content: msg,
            cancelText: "取消",
            confirmText: "去授权",
          );
          if (result ?? false) {
            PermissionUtil.openAppSettings();
          }
        });
    if(list == null || list.isEmpty||list.length <1){
      toast("选择图片失败");
      return;
    }
    fileUrl = list.elementAt(0);
    VgMatisseUploadUtils.uploadSingleImage(
        fileUrl,
        VgBaseCallback(onSuccess: (String netPic) {
          if (StringUtils.isNotEmpty(netPic)) {
            _changeImage?.call(netPic);
          } else {
            VgToastUtils.toast(context, "图片上传失败");
          }
        }, onError: (String msg) {
          VgToastUtils.toast(context, msg);
        }));
  }

  void _chooseSinglePicAndClip(int scalex, int scaley) async {
    String fileUrl =
    await MatisseUtil.clipOneImage(context, scaleX: scalex, scaleY: scaley,
        onRequestPermission: (msg)async{
          bool result =
          await CommonConfirmCancelDialog.navigatorPushDialog(context,
            title: "提示",
            content: msg,
            cancelText: "取消",
            confirmText: "去授权",
          );
          if (result ?? false) {
            PermissionUtil.openAppSettings();
          }
        });
    if (fileUrl == null || fileUrl == "") {
      return null;
    }
    VgMatisseUploadUtils.uploadSingleImage(
        fileUrl,
        VgBaseCallback(onSuccess: (String netPic) {
          if (StringUtils.isNotEmpty(netPic)) {
            _changeImage?.call(netPic);
          } else {
            VgToastUtils.toast(context, "图片上传失败");
          }
        }, onError: (String msg) {
          VgToastUtils.toast(context, msg);
        }));
  }


  _showChangeColorSheet(){
    double sheetHeight = ((((ScreenUtils.screenW(context) - 15 - 16) / 5.5) * 114) / 60) + 8 + 8 + 50+2;
    return Visibility(
      visible: showChangeColorSheet,
      child: Container(
        color: Colors.transparent,
        child: Align(
          alignment: Alignment.bottomCenter,
          child: Container(
            color: Color(0xFFF6F7F9),
            height: sheetHeight,
            child: Column(
              children: [
                SizedBox(height: 8,),
                Container(
                  height: ((((ScreenUtils.screenW(context) - 15 - 16) / 5.5) * 114) / 60),
                  child: GridView.builder(
                      padding: EdgeInsets.only(
                        left: 15,
                        right: 15,
                      ),
                      itemCount: _multiColorList?.length??0,
                      physics: ClampingScrollPhysics(),
                      controller: _horizontalController,
                      scrollDirection:Axis.horizontal,
                      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 1,
                        mainAxisSpacing: 3,
                        crossAxisSpacing: 0,
                        childAspectRatio: 114 / 60,
                      ),
                      itemBuilder: (BuildContext context, int index) {
                        return _toGridItemWidget(context, _multiColorList?.elementAt(index), index);
                      }),
                ),
                SizedBox(height: 8,),
                Row(
                  children: [
                    GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: (){
                        setState(() {
                          if(_selectIndex != _tempSelectIndex){
                            String psdJson = _multiColorList[_selectIndex].dataJson;
                            String js = "get_data('${psdJson}')";
                            _setPsd(js);
                            _tempSelectIndex = _selectIndex;
                            _initPageNotifier.value = _tempSelectIndex;
                          }
                          showChangeColorSheet = !showChangeColorSheet;
                        });
                      },
                      child: Container(
                          padding: EdgeInsets.all(15),
                          child: Image.asset("images/icon_cancel_select_color.png", width: 20,)
                      ),
                    ),
                    Spacer(),
                    GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: (){
                        setState(() {
                          _selectIndex = _tempSelectIndex;
                          showChangeColorSheet = !showChangeColorSheet;
                        });
                      },
                      child: Container(
                          padding: EdgeInsets.all(15),
                          child: Image.asset("images/icon_select_color.png", width: 20,)
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

}
